import { defineStore } from 'pinia';
import { http } from '@/utils/request';
import type { BannerList, CategoryList, newGoodsList } from '@/types';

export const useHomeStore = defineStore('home', {
  // 使用插件开启数据持久化
  persist: {
    // 修改存储中使用的键名称，默认为当前 Store的 id
    key: 'homekey',
    // 按需持久化 默认全部持久化
    paths: ['categoryList', 'bannerList', 'newGoodsList'],
  },
  //  state 对应 vue2 的 data
  state() {
    return {
      categoryList: [] as CategoryList,
      bannerList: [] as BannerList,
      newGoodsList: [] as newGoodsList,
    };
  },
  //  state 对应 vue2 的 computed
  getters: {},

  //  state 对应 vue2 的 methods
  actions: {
    // 导航渲染
    async getAllCategory() {
      // const res = await instance.request<{
      //   code: string;
      //   msg: string;
      //   result: CategoryList;
      // }>({
      //   url: '/home/category/head',
      // });
      const res = await http<CategoryList>('get', '/home/category/head');
      this.categoryList = res.data.result;
    },
    // 轮播图
    async getBannerList() {
      const res = await http<BannerList>('get', '/home/banner');
      this.bannerList = res.data.result;
    },
    // 新鲜好物
    async getNewGoodsList() {
      const res = await http<newGoodsList>('get', '/home/new', { limit: 4 });
      this.newGoodsList = res.data.result;
    },
  },
});
